package com.zhaosc.spark.sql.udf

import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.types.DataType
import org.apache.spark.sql.types.DataTypes
import org.apache.spark.sql.api.java.UDF1

object UDFTest {

  def main(args: Array[String]): Unit = {
    val spark = SparkSession
      .builder()
      .appName("UDFTest")
      .config("spark.master", "local")
      .getOrCreate();

    val list = "Tom" :: "To	m" :: "Jack" :: "Marry" :: "yarn" :: Nil;

    import spark.implicits._;
    val df = spark.sparkContext.parallelize(list).toDF("name");
    
    df.createTempView("t_name")
    
    spark.udf.register("strlen1", (s:String)=>s.length())
    
    val udf1=new UDF1[String,Int]{
      override def call(str:String)=str.length;
    }
    spark.udf.register("strlen2", udf1,DataTypes.IntegerType);
    
    spark.sql("select strlen1(name) from t_name ").show();
    
    spark.sparkContext.stop()

  }
}